#include "client_socket.h"
#include <QDebug>

ClientSocket::ClientSocket(QObject *parent) : QObject(parent) {
    connect(&socket, &QTcpSocket::disconnected, this, [](){
        qDebug() << "连接断开";
    });
}

bool ClientSocket::connectToServer(const QString &host, quint16 port) {
    if (socket.state() == QAbstractSocket::ConnectedState)
        socket.disconnectFromHost();

    socket.connectToHost(host, port);
    return socket.waitForConnected(3000);
}

bool ClientSocket::sendCommand(const QString &cmd) {
    if (socket.state() != QAbstractSocket::ConnectedState)
        return false;

    QByteArray data = cmd.toUtf8() + "\n";
    socket.write(data);
    return socket.waitForBytesWritten(1000);
}

QString ClientSocket::readResponse() {
    if (socket.waitForReadyRead(3000)) {
        QByteArray data = socket.readAll();
        return QString::fromUtf8(data).trimmed();
    }
    return "无响应";
}

void ClientSocket::closeConnection() {
    if (socket.state() == QAbstractSocket::ConnectedState) {
        socket.disconnectFromHost();
        socket.waitForDisconnected(1000);
    }
}
